package com.stars.easyms.logger.support.logback.handler;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.OutputStreamAppender;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * <p>className: EasyMsAsynAppenderEncoderCache</p>
 * <p>description: EasyMsAsynAppenderEncoder缓存池</p>
 *
 * @author guoguifang
 * @date 2019-11-08 12:55
 * @since 1.3.3
 */
@SuppressWarnings("unchecked")
public final class EasyMsAsynAppenderEncoderCache {

    private static final Map<OutputStreamAppender, EasyMsAsynAppenderEncoder> ASYN_APPENDER_WORKER_MAP = new ConcurrentHashMap<>(8);

    public static EasyMsAsynAppenderAddExecutor getAddExecutor(OutputStreamAppender appender, ILoggingEvent event) {
        if (event instanceof EasyMsLoggingEvent) {
            EasyMsLoggingEvent easyMsLoggingEvent = (EasyMsLoggingEvent) event;
            easyMsLoggingEvent.appenderHold();
            final EasyMsAsynAppenderEncoder easyMsAsynAppenderEncoder = ASYN_APPENDER_WORKER_MAP.computeIfAbsent(appender, EasyMsAsynAppenderEncoder::new);
            return () -> easyMsAsynAppenderEncoder.add(easyMsLoggingEvent);
        } else {
            return () -> appender.doAppend(event);
        }
    }

    public static void execute(OutputStreamAppender appender, ILoggingEvent event) {
        if (event instanceof EasyMsLoggingEvent) {
            EasyMsLoggingEvent easyMsLoggingEvent = (EasyMsLoggingEvent) event;
            easyMsLoggingEvent.appenderHold();
            ASYN_APPENDER_WORKER_MAP.computeIfAbsent(appender, EasyMsAsynAppenderEncoder::new).add(easyMsLoggingEvent);
        } else {
            appender.doAppend(event);
        }
    }

    private EasyMsAsynAppenderEncoderCache() {
    }
}